<template>
  <div class="album-detail-container fade-in">
    <!-- 专辑详情卡片 -->
    <div class="album-detail-card content-stagger">
      <!-- 左侧封面区域 -->
      <div class="cover-section scale-in">
        <div class="cover-wrapper" @click="showLargeCover = true">
          <img
            :src="album.coverUrl"
            :alt="album.title"
            class="cover-image"
            @error="handleImageError"
          />
        </div>

        <!-- 专辑统计信息 -->
        <div class="album-stats">
          <div class="stat-item">
            <span class="stat-number">{{ album.musicList?.length || 0 }}</span>
            <span class="stat-label">曲目</span>
          </div>
        </div>
      </div>

      <!-- 右侧信息区域 -->
      <div class="info-section">
        <div class="header-info">
          <h1 class="album-title">{{ album.title || '未命名专辑' }}</h1>
          <p class="album-creator">
            <span>创建者：</span>
            <a href="#" @click.prevent="goToUserProfile(album.creatorId)" class="creator-link">
              {{ album.creatorNickname || album.creatorName || '未知用户' }}
            </a>
          </p>
        </div>

        <!-- 专辑基本信息 -->
        <div class="info-cards">
          <div class="info-card">
            <div class="info-icon">📅</div>
            <div class="info-content">
              <span class="info-label">创建时间</span>
              <span class="info-value">{{ formatDate(album.createTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 专辑描述 -->
        <div class="album-description" v-if="album.description">
          <h3 class="description-title">专辑描述</h3>
          <div class="description-text">
            <p>{{ album.description }}</p>
          </div>
        </div>
        <div class="album-description" v-else>
          <h3 class="description-title">专辑描述</h3>
          <div class="description-text">
            <p>暂无描述</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn btn-primary" @click="playAll" :disabled="!album.musicList?.length">
            播放全部
          </button>
          <button class="btn btn-tertiary" @click="shareAlbum">分享</button>
        </div>
      </div>
    </div>

    <!-- 曲目列表 -->
    <div class="music-list-section content-stagger" v-if="album.musicList?.length > 0">
      <div class="section-header scale-in">
        <h2 class="section-title">
          <i class="el-icon-headset"></i>
          曲目列表
        </h2>
      </div>

      <div class="music-grid">
        <div
          v-for="(music, index) in album.musicList"
          :key="music.id"
          class="music-card"
          :style="{ animationDelay: `${index * 0.1}s` }"
          @click="goToMusicDetail(music.id)"
          style="cursor: pointer;"
        >
          <div class="music-cover">
            <img :src="music.coverUrl" :alt="music.title" />
          </div>

          <div class="music-info">
            <h4 class="music-title">{{ music.title || '未命名音乐' }}</h4>
            <p class="music-artist">{{ music.creatorNickname || music.creatorName || '未知创作者' }}</p>
            <div class="music-meta">
              <span
                class="genre"
                style="
                  background: rgba(46, 204, 113, 0.1);
                  color: #2ecc71;
                  padding: 2px 8px;
                  border-radius: 12px;
                  font-size: 12px;
                "
                >{{ music.genreName || '未知曲风' }}</span
              >
            </div>
          </div>

          <div class="music-actions">
            <button class="action-btn play-btn" @click.stop="playTrack(music, index)">
              <img
                src="/src/assets/icon/play_2.svg"
                alt="播放"
                style="width: 16px; height: 16px; filter: brightness(0) invert(1)"
              />
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state content-stagger" v-else>
      <div class="empty-icon">🎵</div>
      <h3>暂无音乐</h3>
      <p>这个专辑还没有添加任何音乐</p>
    </div>

    <!-- 大图预览 -->
    <div v-if="showLargeCover" class="cover-preview-modal" @click="showLargeCover = false">
      <div class="cover-preview-content" @click.stop>
        <img
          :src="album.coverUrl || 'https://via.placeholder.com/600x600/27ae60/ffffff?text=专辑封面'"
          :alt="album.title"
          class="large-cover-image"
        />
        <button class="close-preview-btn" @click="showLargeCover = false">
          <i class="el-icon-close"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAlbumById } from '@/api/album'
import { getUserInfoById } from '@/api/user'

import { ElMessage } from 'element-plus'
import { useEventBus } from '@/utils/eventBus'

export default {
  name: 'AlbumDetailView',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const album = ref({
      id: null,
      title: '',
      coverUrl: '',
      creatorId: null,
      creatorName: '',
      createTime: '',
      description: '',
      musicList: [],
    })
    const loading = ref(false)
    const showLargeCover = ref(false)



    // 加载专辑数据
    const loadAlbum = async () => {
      loading.value = true
      try {
        const albumId = route.params.id
        const response = await getAlbumById(albumId)

        if (response.code === 200) {
          const albumData = response.data
          
          // 处理专辑创建者昵称
          let creatorNickname = albumData.creatorName || '未知用户'
          if (albumData.creatorId) {
            try {
              const userResponse = await getUserInfoById(albumData.creatorId)
              if (userResponse.data) {
                creatorNickname = userResponse.data.nickname || userResponse.data.username || albumData.creatorName || '未知用户'
              }
            } catch (error) {
              console.error('获取专辑创建者昵称失败:', error)
            }
          }

          // 处理音乐列表的创作者昵称
          let processedMusicList = []
          if (Array.isArray(albumData.musicList)) {
            processedMusicList = await Promise.all(
              albumData.musicList.map(async (music) => {
                let creatorNickname = music.creatorName || '未知创作者'
                let creatorNicknames = [creatorNickname]
                
                const creatorIds = music.creatorIds || music.creator_ids || ''
                if (creatorIds && creatorIds.trim() !== '') {
                  const ids = creatorIds
                    .split('-')
                    .map(id => parseInt(id.trim()))
                    .filter(id => !isNaN(id))
                  
                  if (ids.length > 0) {
                    try {
                      const userPromises = ids.map(id => getUserInfoById(id))
                      const userResponses = await Promise.allSettled(userPromises)
                      
                      const nicknames = userResponses.map((result, index) => {
                        if (result.status === 'fulfilled') {
                          const userData = result.value.data
                          return userData.nickname || userData.username || `用户${ids[index]}`
                        } else {
                          return `用户${ids[index]}`
                        }
                      })
                      
                      creatorNicknames = nicknames
                      creatorNickname = nicknames[0] || '未知创作者'
                    } catch (error) {
                      console.error('获取音乐创作者昵称失败:', error)
                    }
                  }
                }

                return {
                  id: music.id,
                  title: music.title || '未命名音乐',
                  fileUrl: music.fileUrl || '',
                  coverUrl: music.coverUrl || '',
                  creatorName: music.creatorName || '未知艺术家',
                  creatorNickname,
                  creatorNicknames,
                  duration: 0,
                  genreName: music.genreName || '未知曲风',
                }
              })
            )
          }

          album.value = {
            id: albumData.id,
            title: albumData.title || '未命名专辑',
            coverUrl: albumData.coverUrl || '',
            creatorId: albumData.creatorId,
            creatorName: albumData.creatorName || '未知用户',
            creatorNickname,
            createTime: albumData.createTime || '',
            description: albumData.description || '',
            musicList: processedMusicList
          }
        } else {
          ElMessage.error('获取专辑详情失败')
        }
      } catch (error) {
        console.error('加载专辑失败:', error)
        ElMessage.error('加载专辑失败')
      } finally {
        loading.value = false
      }
    }

    // 图片加载错误处理
    const handleImageError = (event) => {
      event.target.style.background = 'linear-gradient(135deg, #2ecc71, #27ae60)'
      event.target.style.display = 'flex'
      event.target.style.alignItems = 'center'
      event.target.style.justifyContent = 'center'
      event.target.style.color = 'white'
      event.target.style.fontWeight = 'bold'
      event.target.textContent = '专辑封面'
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知时间'
      return new Date(dateString).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      })
    }



    // 跳转到用户资料
    const goToUserProfile = (userId) => {
      if (userId) {
        router.push(`/profile/${userId}`)
      }
    }

    // 播放全部
    const eventBus = useEventBus()

    const playAll = () => {
      if (album.value.musicList?.length > 0) {
        eventBus.emit('setPlaylist', album.value.musicList, 0)
        ElMessage.success('开始播放专辑')
      } else {
        ElMessage.warning('专辑中没有音乐')
      }
    }

    // 播放单个曲目
    const playTrack = (music, index) => {
      if (album.value.musicList?.length > 0) {
        eventBus.emit('setPlaylist', album.value.musicList, index)
      }
    }

    // 分享专辑
    const shareAlbum = () => {
      if (album.value) {
        const shareText = `分享专辑：${album.value.title} - ${album.value.creatorName}`
        if (navigator.share) {
          navigator.share({
            title: album.value.title,
            text: shareText,
            url: window.location.href,
          })
        } else {
          navigator.clipboard.writeText(shareText)
          ElMessage.success('分享内容已复制到剪贴板')
        }
      }
    }

    // 跳转到音乐详情页
    const goToMusicDetail = (musicId) => {
      if (musicId) {
        router.push(`/music/${musicId}`)
      }
    }

    onMounted(() => {
      loadAlbum()
    })

    return {
      album,
      loading,
      showLargeCover,
      formatDate,
      handleImageError,
      goToUserProfile,
      playAll,
      playTrack,
      shareAlbum,
      goToMusicDetail,
    }
  },
}
</script>

<style scoped>
.album-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
}

/* 专辑详情卡片 */
.album-detail-card {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 40px;
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(46, 204, 113, 0.08);
  margin-bottom: 40px;
  border: 1px solid rgba(46, 204, 113, 0.1);
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #2ecc71;
}

/* 封面区域 */
.cover-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cover-wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.cover-wrapper:hover .cover-image {
  transform: scale(1.05);
}

/* 专辑统计 */
.album-stats {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 信息区域 */
.info-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.header-info {
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
}

.album-title {
  font-size: 36px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 10px 0;
  line-height: 1.2;
}

.album-creator {
  font-size: 18px;
  color: #7f8c8d;
  margin: 0;
}

.creator-link {
  color: #3498db;
  text-decoration: none;
  transition: color 0.3s ease;
}

.creator-link:hover {
  color: #2980b9;
  text-decoration: underline;
}

/* 信息卡片 */
.info-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.info-card {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background: rgba(46, 204, 113, 0.05);
  border: 1px solid rgba(46, 204, 113, 0.1);
  border-radius: 12px;
  transition: none;
}

.info-card:hover {
  transform: none;
  box-shadow: none;
}

.info-icon {
  font-size: 20px;
  margin-right: 12px;
  color: #2ecc71;
}

.info-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.info-value {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

/* 专辑描述 */
.album-description {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 12px;
}

.description-title {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 15px 0;
}

.description-text {
  font-size: 16px;
  line-height: 1.6;
  color: #666;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.btn {
  display: inline-block;
  padding: 12px 24px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, #2ecc71, #27ae60);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: linear-gradient(135deg, #27ae60, #229954);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(46, 204, 113, 0.3);
}

.btn-secondary {
  background: white;
  color: #2ecc71;
  border: 1px solid #2ecc71;
}

.btn-secondary:hover:not(:disabled) {
  background: #2ecc71;
  color: white;
}

.creator-link {
  color: #2ecc71;
  text-decoration: none;
  transition: color 0.3s ease;
}

.creator-link:hover {
  color: #27ae60;
  text-decoration: underline;
}

.control-btn:hover {
  background: #2ecc71;
  color: white;
  border-color: #2ecc71;
}

.music-card:hover {
  background: white;
  box-shadow: 0 4px 12px rgba(46, 204, 113, 0.1);
  transform: translateY(-2px);
}

.btn-tertiary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
}

.btn-tertiary:hover {
  background: #e9ecef;
}

/* 音乐列表区域 */
.music-list-section {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.list-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  display: flex;
  gap: 10px;
}

.control-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 20px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.control-btn:hover {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

/* 音乐网格 */
.music-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.music-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.music-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(46, 204, 113, 0.15);
  border-color: rgba(46, 204, 113, 0.3);
  background: white;
}

.music-card:hover {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.music-cover {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.music-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.track-number {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.music-info {
  flex: 1;
  min-width: 0;
}

.music-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 4px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.music-artist {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.music-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}



.genre {
  background: rgba(46, 204, 113, 0.1);
  color: #2ecc71;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.music-actions {
  display: flex;
  align-items: center;
}

.action-btn {
  background: rgba(46, 204, 113, 0.1);
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #2ecc71;
}

.action-btn:hover {
  background: #2ecc71;
  transform: scale(1.1);
}

.action-btn:active {
  transform: scale(0.95);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 24px;
  color: #666;
  margin: 0 0 10px 0;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}

/* 大图预览 */
.cover-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  cursor: pointer;
}

.cover-preview-content {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
}

.large-cover-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
}

.close-preview-btn {
  position: absolute;
  top: -40px;
  right: 0;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 50%;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.close-preview-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

/* 动画 */
.fade-in {
  animation: fadeIn 0.6s ease-out forwards;
}

.content-stagger {
  animation: slideUp 0.6s ease-out forwards;
}

.scale-in {
  animation: scaleIn 0.5s ease-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .album-detail-card {
    grid-template-columns: 1fr;
    gap: 30px;
  }

  .cover-section {
    max-width: 300px;
    margin: 0 auto;
  }
}

@media (max-width: 768px) {
  .album-detail-container {
    padding: 15px;
  }

  .album-detail-card {
    padding: 20px;
  }

  .album-title {
    font-size: 28px;
  }

  .music-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .btn {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .album-detail-card {
    padding: 15px;
  }

  .cover-section {
    max-width: 100%;
  }

  .album-title {
    font-size: 24px;
  }

  .info-cards {
    grid-template-columns: 1fr;
  }

  .music-card {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }

  .music-cover {
    width: 80px;
    height: 80px;
    margin: 0 auto;
  }
}
</style>
